package com.c.controller;

import com.alibaba.fastjson.JSON;
import com.c.common.service.RedisService;
import com.c.pojo.entity.User;
import com.c.service.UserService;
import com.c.util.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;


/**
 * @author bysun
 */
@Controller
public class LoginController {

    Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Resource
    UserService userService;

    @Autowired
    RedisService redisService;

    @PostMapping("/userLogin")
    public String goToLogin(HttpServletRequest request,
                            HttpServletResponse response,
                            @RequestParam("username") String username,
                            @RequestParam("pwd") String pwd,
                            Model model) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(pwd)) {
            model.addAttribute("msg", "账户名或密码不可为空");
            return "redirect:index";
        }
        User user = userService.getUserByName(username);
        logger.info("user:{}", user);
        if (user == null || !user.getPwd().equals(pwd)) {
            model.addAttribute("msg", "账户名或密码错误");
            return "redirect:index";
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        CookieUtil.setCookie(request, response, "token", uuid, 7200);
        redisService.set(uuid, JSON.toJSONString(user), 600L);
        return "redirect:getAccounts";
    }

    @GetMapping("/login")
    public String goLogin() {
        return "login";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response) {
        String token = CookieUtil.getCookieValue(request, "token");
        CookieUtil.deleteCookie(request, response, "token");
        redisService.del(token);
        return "redirect:/index";
    }
}
